package moonshot

import (
	"context"
	"fmt"
	"github.com/northes/go-moonshot"
	"roc/wechat/global"
)

type Moonshot struct {
}

var moonshotClient *moonshot.Client

func InitMoonshot() {
	if global.CONFIG.Kimi.Key == `` {
		panic("kimi秘钥未配置")
	}
	cli, err := moonshot.NewClientWithConfig(
		moonshot.NewConfig(
			moonshot.WithAPIKey(global.CONFIG.Kimi.Key),
		),
	)
	if err != nil {
		fmt.Println("moonshot 连接失败")
		return
	}

	moonshotClient = cli

	global.AiClient = Moonshot{}
}

func ShowModels() {
	resp, err := moonshotClient.Models().List(context.Background())
	if err != nil {
		return
	}

	for _, v := range resp.Data {
		fmt.Println(v)
	}
	fmt.Println(resp)
}

// GetDefaultInfo
// @Description: 获取默认的builder
// @receiver m
// @return defaultBuild
func (m Moonshot) GetDefaultInfo() (defaultBuild interface{}) {
	builder := moonshot.NewChatCompletionsBuilder()
	return builder.AddPrompt("你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。").
		SetTemperature(0.3)
}

func (m Moonshot) Chat(msg string, reqBuilder interface{}) (content string, newBuilder interface{}, err error) {
	// Use builder to build a request more conveniently
	builder := reqBuilder.(moonshot.IChatCompletionsBuilder)
	builder.AddUserContent(msg)

	ctx := context.Background()
	resp, err := moonshotClient.Chat().Completions(ctx, builder.ToRequest())
	if err != nil {
		return
	}

	resp, err = moonshotClient.Chat().Completions(ctx, builder.ToRequest())
	if err != nil {
		return
	}

	message := resp.Choices[0].Message
	builder.AddMessage(message)
	newBuilder = builder
	content = message.Content
	return
}

func ChatBak(msg string) (content string, err error) {
	// Use builder to build a request more conveniently
	builder := moonshot.NewChatCompletionsBuilder()
	builder.AddPrompt("你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。").
		AddUserContent("你好，我叫李雷，1+1等于多少？").
		SetTemperature(0.3)

	ctx := context.Background()
	resp, err := moonshotClient.Chat().Completions(ctx, builder.ToRequest())
	if err != nil {
		return
	}
	// {"id":"cmpl-eb8e8474fbae4e42bea9f6bbf38d56ed","object":"chat.completion","created":2647921,"model":"moonshot-v1-8k","choices":[{"index":0,"message":{"role":"assistant","content":"你好，李雷！1+1等于2。这是一个基本的数学加法运算。如果你有任何其他问题或需要帮助，请随时告诉我。"},"finish_reason":"stop"}],"usage":{"prompt_tokens":87,"completion_tokens":31,"total_tokens":118}}

	// do something...

	// append context
	for _, choice := range resp.Choices {
		builder.AddMessage(choice.Message)
	}

	builder.AddUserContent("在这个基础上再加3等于多少")

	resp, err = moonshotClient.Chat().Completions(ctx, builder.ToRequest())
	if err != nil {
		return
	}

	content = resp.Choices[0].Message.Content
	return
}
